package com.byron.pss.dao.impl;

import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.byron.pss.dao.ILostFoundDAO;
import com.byron.pss.domain.LostFound;
import com.byron.pss.domain.LostFoundStr;
import com.byron.pss.template.IResultHandler;
import com.byron.pss.template.JdbcTemplate;
import com.byron.pss.util.Transform;

public class LostFoundDAOImpl implements ILostFoundDAO {

	@Override
	public void save(LostFound lf) {
		String sql = "INSERT INTO lostfound VALUES(NULL,?,?,?,?,?,?)";
		Object[] params = new Object[] { lf.getName(), lf.getDescribe(),
				lf.getLocation(), lf.getLostTime().toLocaleString(),
				lf.getNumber(), lf.getOther() };
//		System.out.println(lf);
		JdbcTemplate.update(sql, params);
	}

	@Override
	public void delete(Long id) {
		String sql = "DELETE FROM lostfound WHERE id=?";
		JdbcTemplate.update(sql, id);
	}

	@Override
	public void update(LostFound lf) {
		String sql = "UPDATE lostfound SET "
				+ "`name`=?,`describe`=?,location=?,losttime=?,number=?,other=? WHERE id=?";
		Object[] params = new Object[] { lf.getName(), lf.getDescribe(),
				lf.getLocation(), lf.getLostTime().toLocaleString(),
				lf.getNumber(), lf.getOther(), lf.getId() };
		JdbcTemplate.update(sql, params);
	}

	@Override
	public List<LostFound> list() {
		String sql = "SELECT * FROM lostfound";
		List<LostFound> list = JdbcTemplate.query(sql, new MyResultHandler());
		return list;
	}

	class MyResultHandler implements IResultHandler<List<LostFound>> {

		@Override
		public List<LostFound> handle(ResultSet rs) throws Exception {
			List<LostFound> list = new ArrayList<>();
			while (rs.next()) {
				LostFound lf = new LostFound();
				lf.setId(rs.getLong("id"));
				lf.setName(rs.getString("name"));
				lf.setDescribe(rs.getString("describe"));
				lf.setLocation(rs.getString("location"));

				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
				Date date = sf.parse(rs.getString("losttime"));
				lf.setLostTime(date);

				lf.setNumber(rs.getInt("number"));
				lf.setOther(rs.getString("other"));
				list.add(lf);
			}
			return list;
		}

	}
}
